using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PackTracker.Business;

public partial class Usuarios : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected override void OnPreRenderComplete(EventArgs e)
    {
        base.OnPreRenderComplete(e);

        ApplyAuthorizationRules();

        memberGrid.DataSource = memberListDataSource;
        memberGrid.DataBind();
    }

    protected void ApplyAuthorizationRules()
    {
        bool isAdministrator = Roles.IsUserInRole(Membership.GetUser().UserName, "Administradores");


        AddNewUser.Visible = isAdministrator;
        memberGrid.Columns[memberGrid.Columns.Count - 1].Visible = isAdministrator;
        memberGrid.Columns[memberGrid.Columns.Count - 2].Visible = isAdministrator;
    }

    protected void AddNewUser_Click(object sender, EventArgs e)
    {
        ResetAddUserForm();
        NewUserModalPopupExtender.Show();
        ScriptManager.GetCurrent(this.Page).SetFocus(txtLoginName);
    }

    protected void btnAddUserOK_Click(object sender, EventArgs e)
    {
        MembershipCreateStatus status;
        MembershipUser user = Membership.CreateUser(txtLoginName.Text, txtPassword.Text, txtEmail.Text, txtSecurityQuestion.Text, txtSecurityAnswer.Text, true, out status);
        if (user != null)
        {
            user.Comment = txtUserName.Text;
            Membership.UpdateUser(user);

            Usuario usuario = Usuario.NewUsuario();
            usuario.Bloqueado = false;
            usuario.Login = txtLoginName.Text;
            usuario.Senha = txtPassword.Text;
            usuario.Save();
        }

        memberGrid.DataBind();
    }
    protected void memberGrid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DELETE")
        {

            Usuario usuario = Usuario.GetUsuario(e.CommandArgument.ToString());

            UsuarioCollection usuarios = UsuarioCollection.GetUsuarioCollection();
            usuarios.Remove(usuario);
            usuarios.Save();

            Membership.DeleteUser(e.CommandArgument.ToString());

            

            memberGrid.DataBind();
        }
        else if (e.CommandName == "MODIFYROLES")
        {
            string userName = e.CommandArgument.ToString();
            ViewState["UserName"] = userName;
            BindRoleGrid();

            UserRolesModalPopupExtender.Show();
        }
    }

    protected void memberGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    }

    protected void roleGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string userName = ViewState["UserName"].ToString();
            string roleName = ((string)e.Row.DataItem);
            ((Label)e.Row.FindControl("roleName")).Text = roleName;
            ((CheckBox)e.Row.FindControl("inThisRole")).Checked = Roles.IsUserInRole(userName, roleName);
        }
    }

    protected void btnSaveUserRoles_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in roleGrid.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                string roleName = ((Label)row.FindControl("roleName")).Text;
                string userName = ViewState["UserName"].ToString();

                if (((CheckBox)row.FindControl("inThisRole")).Checked)
                {
                    if (!Roles.IsUserInRole(userName, roleName))
                        Roles.AddUserToRole(userName, roleName);
                }
                else
                {
                    if (Roles.IsUserInRole(userName, roleName))
                        Roles.RemoveUserFromRole(userName, roleName);
                }
            }
        }
        UserRolesModalPopupExtender.Hide();
    }

    private void BindRoleGrid()
    {
        roleGrid.DataSource = Roles.GetAllRoles();
        roleGrid.DataBind();
    }

    private void ResetAddUserForm()
    {
        txtLoginName.Text           = "";
        txtUserName.Text            = "";
        txtPassword.Text            = "";
        txtPassword2.Text           = "";
        txtEmail.Text               = "";
        txtSecurityQuestion.Text    = "";
        txtSecurityAnswer.Text      = "";
    }

    protected void memberListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = Membership.GetAllUsers();
    }
}

